﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace gecommon
{
    //一个线程安全的队列 使用条件变量 多生产者 多消费者安全
    public class WaitFreeQueue<T>: IReadWriter<T>
    {
        private object _locker = new object();

        private Queue<T> _queue = new Queue<T>();

        public void Enqueue(T item)
        {
            lock (_locker)
            {
                _queue.Enqueue(item);
                Monitor.PulseAll(_locker);
            }
        }

        public T Dequeue()
        {
            T item = default(T);
            lock (_locker)
            {
                while(_queue.Count == 0)
                {
                    Monitor.Wait(_locker);
                }
                item = _queue.Dequeue();
            }
            return item;
        }

        public async Task WriteAsync(T ob)
        {
            Enqueue(ob);
        }

        public async Task<T> ReadAsync()
        {
            return Dequeue();
        }
    }
}
